import React, { useState } from "react"
import { Form, Input, Button, message, Modal } from "antd"
import './index.less'
import { useNavigate, Navigate } from "react-router-dom"
import { loginProp } from "./types"
import { userLogin, userReg } from "@/realApi"


const Login = () => {
    // 控制注册对话框开关
    const [regModalOpen, setRegModalOpen] = useState<boolean>(false)
    // 创建form实例
    const [form] = Form.useForm()
    const navigate = useNavigate()
    // 在登录状态下，需要跳转到home页面
    if (localStorage.getItem('Authorization')) {
        return <Navigate to="/home" replace />
    }

    // 处理登录的回调函数
    const handleSubmit = (val: loginProp) => {
        if (!val.username || !val.password) {
            return message.open({
                type: 'warning',
                content: '请输入用户名和密码'
            })
        }
        userLogin(val).then(({ data: { code, message: errMsg, token } }) => {
            if (code === 20000) {
                localStorage.setItem('Authorization', token)
                navigate('/home')
            }
            else {
                return message.open({
                    type: 'error',
                    content: errMsg
                })
            }
        })
    }

    // 确定注册的回调函数
    const handleOk = () => {
        form.validateFields().then((val) => {
            const regProp = {username: val.regUsername, password: val.regPassword}
            userReg(regProp).then((data) => {
                const {code, message: mentionMsg} = data.data
                if(code === 20000) {
                    message.open({
                        type: 'success',
                        content: mentionMsg
                    })
                    handleCancel()
                }
                else {
                    message.open({
                        type: 'error',
                        content: mentionMsg
                    })
                }
            })
        })
     }

    // 取消注册的回调函数
    const handleCancel = () => {
        setRegModalOpen(false)
        form.resetFields()
    }

    return (
        <>
            <Form className="login-container" onFinish={handleSubmit}>
                <div className="login_title">系统登录</div>
                <Form.Item
                    label="账号"
                    name="username"
                >
                    <Input placeholder="请输入账号" />
                </Form.Item>
                <Form.Item
                    label="密码"
                    name="password"
                >
                    <Input.Password placeholder="请输入密码" />
                </Form.Item>
                <Form.Item className="login-button">
                    {/* 占位div，让登录和注册按钮在一行排列 */}
                    <div style={{ width: 60 }} />
                    <Button type="primary" htmlType="submit">登录</Button>
                    <Button type="link" onClick={() => setRegModalOpen(true)}>注册</Button>
                </Form.Item>
            </Form>
            <Modal
                open={regModalOpen}
                title='用户注册'
                onOk={handleOk}
                onCancel={handleCancel}
                okText='注册'
                cancelText='取消'
            >
                <Form
                    form={form}
                    labelCol={{
                        span: 4
                    }}
                    wrapperCol={{
                        span: 20
                    }}
                    labelAlign="left"
                >
                    <Form.Item
                        label="用户名"
                        name="regUsername"
                        rules={[
                            {
                                required: true,
                                message: '请输入用户名'
                            },
                            { pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不支持特殊字符或空格!' }
                        ]}
                    >
                        <Input placeholder='请输入用户名' />
                    </Form.Item>
                    <Form.Item
                        label="密码"
                        name="regPassword"
                        rules={[
                            {
                                required: true,
                                message: '请输入密码'
                            },
                            { pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不支持特殊字符或空格!' }
                        ]}
                    >
                        <Input.Password placeholder='请输入密码' />
                    </Form.Item>
                    <Form.Item
                        label="确认密码"
                        name="newRegPassword"
                        rules={[
                            {
                                required: true,
                                message: '请输入密码'
                            },
                            { pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不支持特殊字符或空格!' },
                            ({ getFieldValue }) => ({
                                validator(_, value: string) {
                                    if (!value || (getFieldValue('regPassword') === value)) {
                                        return Promise.resolve()
                                    }
                                    return Promise.reject(new Error('两次密码请保持一致!'))
                                }
                            })
                        ]}
                    >
                        <Input.Password placeholder='请再次确认密码' />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}

export default Login